import { topPlaySongLyric, songUrl } from "@/api/api";
import { Commit } from "vuex";
export interface DictState {
  songDetail: object;
  songLyric: object;
  songPlayDetail: object;
  isPlayed: boolean;
  playList: Array<object>;
  songPlayIndex: number;
}

const song = {
  state: (): DictState => ({
    songDetail: { url: "" },
    songLyric: {},
    songPlayDetail: {},
    isPlayed: false, //当前播放状态
    playList: [], //播放列表
    songPlayIndex: 0, //当前播放歌曲下标
  }),
  mutations: {
    setPlayStatus(state: DictState, isPlayed: boolean) {
      state.isPlayed = isPlayed;
    },
    setSongPlayIndex(state: DictState, songPlayIndex: number) {
      state.songPlayIndex = songPlayIndex;
      window.localStorage.setItem("playIndex", JSON.stringify(songPlayIndex));
    },
    setPlayList(state: DictState, playList: Array<object>) {
      state.playList = playList;
      window.localStorage.setItem("playList", JSON.stringify(playList));
    },
    setSongDetail(state: DictState, songDetail: object) {
      state.songDetail = songDetail;
    },
    setSongLyric(state: DictState, songLyric: object) {
      state.songLyric = songLyric;
    },
    setSongPlay(state: DictState, songPlayDetail: object) {
      state.songPlayDetail = songPlayDetail;
    },
  },
  getters: {
    playList(state: DictState) {
      const playListString = window.localStorage.getItem("playList");
      return state.playList.length
        ? state.playList
        : JSON.parse(playListString || "[]");
    },
    songPlayIndex(state: DictState) {
      const playIndexString = window.localStorage.getItem("playIndex");
      return (
        state.songPlayIndex ||
        (playIndexString ? JSON.parse(playIndexString) : 0)
      );
    },
  },
  actions: {
    async getSongDetail({ commit }: { commit: Commit }, id: number) {
      const aw = await topPlaySongLyric(id);
      commit("setSongLyric", aw);
    },
    async getSongUrl({ commit }: { commit: Commit }, id: string) {
      const aw = await songUrl(id, "lossless");
      commit("setSongDetail", aw.data[0]);
    },
  },
};

export default song;
